package com.tpshion.deploy.interceptor;

import com.tpshion.deploy.common.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import java.util.Map;

@Slf4j
@Component
public class WebSocketInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        HttpHeaders headers = request.getHeaders();
        log.info("beforeHandshake headers:{}", headers);
        String taskId = request.getHeaders().getFirst(Constant.TASK_ID);
        if(!StringUtils.hasText(taskId)){
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return false;
        }

        attributes.put(Constant.TASK_ID, taskId);
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        log.info("afterHandshake exception:{}", exception);
    }
}
